
#include <errno.h>
#include <stdint.h>

#include "network/AbstractClient.h"
#include "network/Server.h"

extern int errno;

AbstractClient::AbstractClient(Server* server)
    : AbstractThread(), AbstractIOSocket(), pServer_(server)
{
}

AbstractClient::~AbstractClient()
{
    close();
}

bool AbstractClient::close()
{
    bool isClosed = AbstractSocket::close();

    // Maj des références.
    pServer_->mutex_.lock();
    if(isClosed)
        pServer_->clients_.erase(this);
    pServer_->mutex_.unlock();

    return isClosed;
}

bool AbstractClient::connect()
{
    if(isOpen())
        close();

    // Acceptation du prochain client
    length_ = sizeof(sin_);
    iSocket_ = accept(pServer_->iSocket_, (struct sockaddr*)&sin_, &length_);
    if(iSocket_ < 0)
    {
        iError_ = errno;
        return false;
    }

    // Maj des références
    pServer_->mutex_.lock();
    pServer_->clients_.insert(this);
    pServer_->mutex_.unlock();

    // Rendre la socket ouverte
    isOpen_ = true;

    return true;
}
